import React from 'react';
import { connect } from 'react-redux';
import { Button, Row, Col, message, Tooltip, Switch } from 'antd';
import List from './list';
import CommonListsIndex from 'src/components/CommonLists/index';
import FilterTool from 'src/components/FilterTool';
import Add from './add';
import services from 'src/services/api';
import CodeLabel from 'src/components/CodeLabel';
import AuditStatus from 'src/components/AuditStatus';
import storage from 'src/utils/storage';
import { AUDIT, ENABLE_STATUS } from 'src/utils/constant';
import RelationStrategy from '../relation';
import Modal from 'src/components/Modal/index';

function mapStateToProps(state) {
  return {
    strategy_type: state.code.strategy_type || [],
    strategy_mode: state.code.strategy_mode || [],
  };
}

@connect(mapStateToProps)
class StrategyComponent extends CommonListsIndex {
  constructor(props) {
    super(props);
    this.api = 'strategyComponent';
    this.addComponent = Add;
    this.editComponent = '/strategy/component/id/edit';
    this.copyComponent = '/strategy/component/id/copy';
    this.detailComponent = '/strategy/component/id/detail';
    this.listsComponent = List;
    this.state = {
      ...this.state,
      riskTypes: [],
      columns: [],
      dataIndex: 'strategy_type',
      defaultColumns: [
        'name',
        'app_name',
        'product_name',
        'event_name',
        'version',
        'status',
        'audit_label',
        'strategy_mode',
        'create_user_name',
        'update_time',
        // 'risk_type',
        'strategy_type_name',
        'strategy_nums'
      ],
      selectedRowKeys: [],
      currentEventId: '',
      selectedRows: [],
    };
    if (this.app_id) {
      this.queryTableParams.app_id = this.app_id;
    }
    if (this.event_id) {
      this.queryTableParams.event_id = this.event_id;
    }
    if (this.field_id) {
      this.queryTableParams.field_id = this.field_id;
    }
    if (this.feature_id) {
      this.queryTableParams.feature_id = this.feature_id;
    }
  }
  componentDidMount() {
    this.getAppCodeList();
    this.getProductCodeList();
    this.getRiskTypeList();
    // storage.strategyExport = []; // 首次进入清空storage.strategyExport
  }

  // 打开新窗口、页面的id
  getOpenParam = (record) => {
    return record.strategy_id;
  };

  // 获取风险类型列表
  getRiskTypeList = () => {
    services.policy.riskTypeList().then((res) => {
      if (res.code === 0) {
        this.setState({
          riskTypes: res.data,
        });
      }
    });
  };

  // 策略导入回调
  onChange = (info) => {
    this.freshQueryList();
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} 导入成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 导入失败`);
    }
  };

  // 关联策略
  showRelationStrategy = record => {
    Modal.open({
      title: <>关联策略<span style={{ fontSize: 10, color: 'grey', marginLeft: 4 }}>仅展示当前部门拥有权限数据</span></>,
      width: '1000px',
      content: (
        <RelationStrategy record={record} param={{
          custom_field_id: record.strategy_id,
          strategy_type: 2,
          type: 'component',
          app_id: record.app_id,
          event_id: record.event_id }} />
      ),
      isOkBtn: true,
      maskClosable: false,
      isCancelBtn: true,
      ok: () => Modal.close()
    });
  };

  // 详情
  showDetail = (record) => {
    this.props.history.push(this.replaceUrlForId(this.detailComponent, this.getOpenParam(record)));
  };

  // 复制
  copy = (record) => {
    this.props.history.push(this.replaceUrlForId(this.copyComponent, this.getOpenParam(record)));
  };

  // 表列定义
  getColumns = () => {
    return [
      {
        title: '组件名称',
        key: 'name',
        dataIndex: 'name',
        width: 90,
        ellipsis: true,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              <div className="overflowtext">
                <Button type='link' onClick={() => this.showDetail(record)}>
                  {text}
                </Button>
              </div>
            </Tooltip>
          );
        },
      },

      {
        title: (
          <>
            {this.getFilterTitle(
              '所属渠道',
              this.state.applications,
              'app_id',
              this.refreshTableFilterWithAppV2.bind(this, 'app_id'),
              ['app_id', 'app_name']
            )}
          </>
        ),
        dataIndex: 'app_name',
        key: 'app_name',
        width: 90,
        ellipsis: true,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
      },
      {
        title: (
          <>
            {this.getFilterTitle(
              '关联产品',
              this.state.products,
              'product_id',
              this.refreshTableFilterWithAppV2.bind(this, 'product_id'),
              ['product_id', 'product_name']
            )}
          </>
        ),
        dataIndex: 'product_name',
        key: 'product_name',
        width: 90,
        ellipsis: true,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
      },
      {
        title: (
          <>
            {this.getFilterTitle(
              '关联事件',
              this.state.events,
              'event_id',
              this.refreshTableFilterWithAppV2.bind(this, 'event_id'),
              ['event_id', 'event_name']
            )}
          </>
        ),
        dataIndex: 'event_name',
        key: 'event_name',
        width: 90,
        ellipsis: true,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
      },
      {
        title: (
          <>
            {this.getFilterTitle(
              '组件模式',
              this.props.strategy_mode,
              'strategy_mode',
              this.refreshTableFilterWithApp,
              ['key', 'value']
            )}
          </>
        ),
        key: 'strategy_mode',
        dataIndex: 'strategy_mode',
        width: 90,
        ellipsis: true,
        render: (text) => {
          return (
            <Tooltip title={<CodeLabel code='strategy_mode' value={text} />}>
              <div className='overflowtext'>
                <CodeLabel code='strategy_mode' value={text} />
              </div>
            </Tooltip>
          );
        },
      },
      {
        title: '当前版本',
        key: 'version',
        dataIndex: 'version',
        ellipsis: true,
        render: (text, record) => {
          return (
            <span style={{ color: '#00a600' }}>{'v' + text}</span>
          );
        },
      },
      {
        title: '关联策略',
        dataIndex: 'strategy_nums',
        key: 'strategy_nums',
        ellipsis: true,
        render: (text, record) => {
          return (
            <Button type='link' onClick={this.showRelationStrategy.bind(this, record)}>
              {text}
            </Button>
          );
        }
      },
      {
        title: (
          <>
            {this.getFilterTitle(
              '状态',
              [
                {
                  value: -1,
                  name: '全部',
                },
                {
                  value: '1',
                  name: '启用',
                },
                {
                  value: '2',
                  name: '未启用',
                },
              ],
              'status',
              this.refreshTableFilterWithApp,
              ['value', 'name']
            )}
          </>
        ),
        key: 'status',
        dataIndex: 'status',
        width: 60,
        ellipsis: true,
        render: (text) => {
          return <Switch checked={text === ENABLE_STATUS._TRUE} disabled></Switch>;
        },
      },

      {
        title: '审核情况',
        key: 'audit_label',
        dataIndex: 'audit_label',
        width: 90,
        ellipsis: true,
        render: (text, record) => {
          return <AuditStatus text={text} record={record} />;
        },
      },

      {
        title: '创建/修改人',
        key: 'create_user_name',
        dataIndex: 'create_user_name',
        ellipsis: true,
        render: (text, record) => {
          var content = !!record.update_user_name
            ? `${record.create_user_name}/${record.update_user_name}`
            : `${record.create_user_name}/${record.create_user_name}`;
          return (
            <Tooltip title={content} placement='topLeft'>
              {content}
            </Tooltip>
          );
        },
      },
      {
        title: '修改时间',
        key: 'update_time',
        dataIndex: 'update_time',
        ellipsis: true,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
      },
    ];
  };

  export = () => {
    if (this.state.selectedRowKeys.length === 0) {
      message.warning('请选择要导出的组件');
      return;
    }
    const params = {
      strategy_ids: this.state.selectedRowKeys.join(),
      event_id: this.state.currentEventId.toString(),
    };
    services.strategyComponent
      .submit(params)
      .then((res) => {
        if (!res.code) {
          this.props.history.push('/strategy/component/export');
        } else {
          message.error(res.msg);
        }
      })
      .catch((err) => {
        message.error(err);
      });
    // console.log('数据', this.state.selectedRowKeys)
  };

  // 删除回调
  deleteCb = (record) => {
    const { selectedRowKeys, selectedRows } = this.state
    if (selectedRowKeys.length === 0) return
    if (selectedRowKeys.indexOf(record.strategy_id) !== -1) {
      let newKeys = selectedRowKeys.filter((item) => item !== record.strategy_id)
      let newRows = selectedRows.filter(item => item.strategy_id !== record.strategy_id)
      if (newKeys.length === 0) this.setState({ currentEventId: '' })
      this.setState(
        {
          selectedRowKeys: newKeys,
          selectedRows: newRows,
        },
        () => {
          const exportMsg = {
            selectedRowKeys: this.state.selectedRowKeys,
            currentEventId: this.state.currentEventId,
          };
          storage.strategyExportMsg = exportMsg;
        }
      );
    }
  }

  render() {
    const ListsComponent = this.listsComponent;
    const data = [
      {
        type: 'Search',
        key: 'keyword',
        name: 'keyword',
        defaultValue: '',
        placeholder: '请输入组件名|创建人|修改人进行搜索',
      },
    ];
    // 字段选择配置
    const rowSelection = {
      columnWidth: 30,
      onChange: (selectedRowKeys, selectedRows) => {
        const f = [...new Set([...selectedRowKeys, ...selectedRows.map((item) => item.strategy_id)])];
        const fx = [...this.state.selectedRows, ...selectedRows];
        const rows = f.map((id) => {
          return fx.find((it) => it.strategy_id === id);
        });

        // 被选中的大于1条时
        if (rows.length > 1) {
          const event_id = rows[0].event_id;
          const isSame = rows.every((it) => it.event_id === event_id); //返回是否全部的event_id都一样
          //  如果一样,则选中
          if (isSame) {
            this.setState(
              {
                selectedRowKeys: f,
                selectedRows: rows,
                currentEventId: event_id,
              },
              () => {
                // storage.strategyExport = rows;
                const exportMsg = {
                  selectedRowKeys: this.state.selectedRowKeys,
                  currentEventId: this.state.currentEventId,
                };
                storage.strategyExportMsg = exportMsg;
              }
            );
          } else {
            message.warning('请选择同一事件下的策略');
          }
        } else {
          if (!this.state.currentEventId) {
            if (rows.length === 1) {
              this.setState({
                currentEventId: rows[0].event_id,
              });
            }
          } else {
            //取消选择，被选中的为0
            if (rows.length === 0) {
              this.setState({
                currentEventId: '',
              });
            }
          }
          this.setState(
            {
              selectedRowKeys: f,
              selectedRows: rows,
            },
            () => {
              // storage.strategyExport = rows;
              const exportMsg = {
                selectedRowKeys: this.state.selectedRowKeys,
                currentEventId: this.state.currentEventId,
              };
              storage.strategyExportMsg = exportMsg;
            }
          );
        }
      },
      getCheckboxProps: (record) => {
        return {
          disabled:
            record.audit_status === AUDIT._WAIT ||
            !!(this.state.currentEventId && record.event_id !== this.state.currentEventId),
        };
      },
      selectedRowKeys: this.state.selectedRowKeys,
    };
    return (
      <div>
        <Row type='flex' justify='space-between' align='middle'>
          <Col span={12}>
            <Button
              type='primary'
              onClick={() => {
                this.props.history.push('/strategy/component/add');
              }}
            >
              新建策略组件
            </Button>
            <Button
              className='marl10'
              onClick={() => {
                this.props.history.push('/strategy/component/import');
              }}
            >
              导入组件
            </Button>
            <Button onClick={this.export} className='marl10'>
              导出组件
            </Button>
          </Col>
          <Col span={12}>
            {this.props.strategy_type && (
              <FilterTool
                ref='filterTool'
                data={data}
                colNum={1}
                query={this.freshQueryList}
                refreshFilter={this.refreshFilter}
                isOnChange={true}
                refresh={this.resetList}
                justify='end'
                columns={this.getColumns()}
                setColumn={this.setColumn}
                defaultColumns={this.state.defaultColumns}
              />
            )}
          </Col>
        </Row>
        <div className='inner-content' style={{ marginTop: '10px' }}>
          <ListsComponent
            rowSelection={rowSelection}
            {...this.state}
            {...this.props}
            edit={this.edit}
            onChangePagination={this.onChangePagination}
            showDetail={this.showDetail}
            copy={this.copy}
            defaultColumns={this.state.defaultColumns}
            columns={this.getColumns()}
            queryList={this.freshQueryList}
            rowKey='strategy_id'
            deleteCb={this.deleteCb}
          />
        </div>
      </div>
    );
  }
}

export default StrategyComponent;
